import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'

const ERROR_MESSAGES = {
  'EMPTY_CODE': '代码不能为空',
  'SERVICE_UNAVAILABLE': 'AI服务暂时不可用',
  'SERVICE_CONFIG_ERROR': 'AI服务配置错误',
  'SERVICE_CLIENT_ERROR': 'AI服务请求错误',
  'SERVICE_ERROR': 'AI服务调用失败',
  'DEFAULT': '代码优化失败'
}

export const useComponentStore = defineStore('component', {
  state: () => ({
    // 定义组件之间的连接规则
    connectionRules: {
      adjacencyMatrix: {
        outputs: ['dijkstra', 'bfs', 'dfs', 'prim', 'kruskal'],
        description: '可以连接到图算法组件'
      },
      adjacencyList: {
        outputs: ['dijkstra', 'bfs', 'dfs', 'prim', 'kruskal'],
        description: '可以连接到图算法组件'
      },
      array: {
        outputs: ['bubbleSort', 'quickSort', 'mergeSort', 'binarySearch', 'heapSort', 'insertionSort', 'selectionSort'],
        description: '可以连接到排序和查找算法组件'
      },
      binaryTree: {
        outputs: ['bfs', 'dfs'],
        description: '可以连接到树遍历算法组件'
      },
      heap: {
        outputs: ['bubbleSort', 'quickSort', 'mergeSort'],
        description: '可以连接到排序算法组件'
      }
    },

    components: [
      // 数据结构组件
      {
        id: 1,
        type: 'adjacencyMatrix',
        name: '邻接矩阵',
        icon: 'Menu',
        config: {
          vertexCount: 5,
          directed: false,
          weighted: true,
          matrix: []
        }
      },
      {
        id: 2,
        type: 'adjacencyList',
        name: '邻接表',
        icon: 'List',
        config: {
          vertexCount: 5,
          directed: false,
          weighted: true,
          lists: []
        }
      },
      {
        id: 3,
        type: 'array',
        name: '数组',
        icon: 'List',
        config: {
          size: 10,
          elementType: 'int',
          elements: []
        }
      },
      {
        id: 4,
        type: 'binaryTree',
        name: '二叉树',
        icon: 'Share',
        config: {
          nodeCount: 7,
          values: []
        }
      },
      {
        id: 5,
        type: 'heap',
        name: '堆',
        icon: 'Sort',
        config: {
          type: 'max', // max or min
          values: []
        }
      },
      {
        id: 6,
        type: 'stack',
        name: '栈',
        icon: 'Files',
        config: {
          maxSize: 10,
          elements: []
        }
      },
      {
        id: 7,
        type: 'queue',
        name: '队列',
        icon: 'Operation',
        config: {
          maxSize: 10,
          elements: []
        }
      },
      // 算法组件
      {
        id: 8,
        type: 'dijkstra',
        name: '迪杰斯特拉算法',
        icon: 'Connection',
        config: {
          startVertex: 0,
          endVertex: 4
        }
      },
      {
        id: 9,
        type: 'bubbleSort',
        name: '冒泡排序',
        icon: 'Sort',
        config: {
          order: 'asc'
        }
      },
      {
        id: 10,
        type: 'bfs',
        name: '广度优先搜索',
        icon: 'Search',
        config: {
          startVertex: 0
        }
      },
      {
        id: 11,
        type: 'quickSort',
        name: '快速排序',
        icon: 'Sort',
        config: {
          pivotStrategy: 'middle'
        }
      },
      {
        id: 12,
        type: 'dfs',
        name: '深度优先搜索',
        icon: 'Search',
        config: {
          startVertex: 0
        }
      },
      {
        id: 13,
        type: 'mergeSort',
        name: '归并排序',
        icon: 'Sort',
        config: {
          order: 'asc'
        }
      },
      {
        id: 14,
        type: 'prim',
        name: 'Prim算法',
        icon: 'Connection',
        config: {
          startVertex: 0
        }
      },
      {
        id: 15,
        type: 'kruskal',
        name: 'Kruskal算法',
        icon: 'Connection',
        config: {}
      },
      {
        id: 16,
        type: 'binarySearch',
        name: '二分查找',
        icon: 'Search',
        config: {
          target: 0
        }
      }
    ],
    codeTemplates: {
      adjacencyMatrix: {
        java: `
public class Graph {
    private int[][] matrix;
    private int vertices;
    private boolean directed;
    private boolean weighted;

    public Graph(int vertices, boolean directed, boolean weighted) {
        this.vertices = vertices;
        this.directed = directed;
        this.weighted = weighted;
        this.matrix = new int[vertices][vertices];
    }

    public void addEdge(int from, int to, int weight) {
        matrix[from][to] = weight;
        if (!directed) {
            matrix[to][from] = weight;
        }
    }

    public int getWeight(int from, int to) {
        return matrix[from][to];
    }

    public boolean hasEdge(int from, int to) {
        return matrix[from][to] != 0;
    }
}
`,
        c: `
typedef struct {
    int** matrix;
    int vertices;
    int directed;
    int weighted;
} Graph;

Graph* createGraph(int vertices, int directed, int weighted) {
    Graph* graph = (Graph*)malloc(sizeof(Graph));
    graph->vertices = vertices;
    graph->directed = directed;
    graph->weighted = weighted;
    graph->matrix = (int**)malloc(vertices * sizeof(int*));
    for (int i = 0; i < vertices; i++) {
        graph->matrix[i] = (int*)calloc(vertices, sizeof(int));
    }
    return graph;
}

void addEdge(Graph* graph, int from, int to, int weight) {
    graph->matrix[from][to] = weight;
    if (!graph->directed) {
        graph->matrix[to][from] = weight;
    }
}

int getWeight(Graph* graph, int from, int to) {
    return graph->matrix[from][to];
}

int hasEdge(Graph* graph, int from, int to) {
    return graph->matrix[from][to] != 0;
}

void freeGraph(Graph* graph) {
    for (int i = 0; i < graph->vertices; i++) {
        free(graph->matrix[i]);
    }
    free(graph->matrix);
    free(graph);
}
`,
        cpp: `
class Graph {
private:
    std::vector<std::vector<int>> matrix;
    int vertices;
    bool directed;
    bool weighted;

public:
    Graph(int vertices, bool directed, bool weighted) 
        : vertices(vertices), directed(directed), weighted(weighted) {
        matrix.resize(vertices, std::vector<int>(vertices, 0));
    }

    void addEdge(int from, int to, int weight) {
        matrix[from][to] = weight;
        if (!directed) {
            matrix[to][from] = weight;
        }
    }

    int getWeight(int from, int to) const {
        return matrix[from][to];
    }

    bool hasEdge(int from, int to) const {
        return matrix[from][to] != 0;
    }
};
`
      },
      array: {
        java: `
public class Array {
    private int[] data;
    private int size;

    public Array(int size) {
        this.size = size;
        this.data = new int[size];
    }

    public void set(int index, int value) {
        if (index >= 0 && index < size) {
            data[index] = value;
        }
    }

    public int get(int index) {
        if (index >= 0 && index < size) {
            return data[index];
        }
        return -1;
    }

    public int getSize() {
        return size;
    }
}
`,
        c: `
typedef struct {
    int* data;
    int size;
} Array;

Array* createArray(int size) {
    Array* arr = (Array*)malloc(sizeof(Array));
    arr->size = size;
    arr->data = (int*)malloc(size * sizeof(int));
    return arr;
}

void setValue(Array* arr, int index, int value) {
    if (index >= 0 && index < arr->size) {
        arr->data[index] = value;
    }
}

int getValue(Array* arr, int index) {
    if (index >= 0 && index < arr->size) {
        return arr->data[index];
    }
    return -1;
}

void freeArray(Array* arr) {
    free(arr->data);
    free(arr);
}
`,
        cpp: `
class Array {
private:
    std::vector<int> data;
    int size;

public:
    Array(int size) : size(size) {
        data.resize(size);
    }

    void set(int index, int value) {
        if (index >= 0 && index < size) {
            data[index] = value;
        }
    }

    int get(int index) const {
        if (index >= 0 && index < size) {
            return data[index];
        }
        return -1;
    }

    int getSize() const {
        return size;
    }
};
`
      },
      dijkstra: {
        java: `
public class Dijkstra {
    private Graph graph;
    private int[] distance;
    private boolean[] visited;
    private int[] previous;

    public Dijkstra(Graph graph) {
        this.graph = graph;
        this.distance = new int[graph.vertices];
        this.visited = new boolean[graph.vertices];
        this.previous = new int[graph.vertices];
    }

    public void findShortestPath(int start, int end) {
        // 初始化
        Arrays.fill(distance, Integer.MAX_VALUE);
        Arrays.fill(visited, false);
        Arrays.fill(previous, -1);
        distance[start] = 0;

        for (int i = 0; i < graph.vertices; i++) {
            int u = getMinUnvisitedVertex();
            if (u == -1) break;
            visited[u] = true;

            for (int v = 0; v < graph.vertices; v++) {
                if (!visited[v] && graph.hasEdge(u, v)) {
                    int alt = distance[u] + graph.getWeight(u, v);
                    if (alt < distance[v]) {
                        distance[v] = alt;
                        previous[v] = u;
                    }
                }
            }
        }
    }

    private int getMinUnvisitedVertex() {
        int min = Integer.MAX_VALUE;
        int minVertex = -1;
        for (int v = 0; v < graph.vertices; v++) {
            if (!visited[v] && distance[v] < min) {
                min = distance[v];
                minVertex = v;
            }
        }
        return minVertex;
    }
}
`
      }
    }
  }),
  
  actions: {
    async generateCode(components, connections, language = 'java') {
      try {
        // 生成唯一的请求ID
        const requestId = Date.now().toString();
        
        // 查找连接中的数据结构和算法
        const dataStructures = ['adjacencyMatrix', 'adjacencyList', 'array', 'binaryTree', 'heap']
        const algorithms = ['dijkstra', 'bubbleSort', 'bfs', 'quickSort', 'dfs', 'mergeSort', 'prim', 'kruskal', 'binarySearch']
        
        // 从连接中找出数据结构节点和算法节点
        const connectedNodes = new Set(connections.flatMap(conn => [conn.source, conn.target]))
        const usedNodes = components.filter(node => connectedNodes.has(node.id))
        const dataStructureNodes = usedNodes.filter(node => dataStructures.includes(node.type))
        const algorithmNodes = usedNodes.filter(node => algorithms.includes(node.type))
        
        // 如果找不到对应的数据结构或算法，返回错误
        if (dataStructureNodes.length === 0 || algorithmNodes.length === 0) {
          throw new Error('请确保至少有一个数据结构和一个算法相连接')
        }
        
        // 构建提示词
        const prompt = this.buildPrompt(dataStructureNodes, algorithmNodes, connections, language, requestId)
        
        // 调用 AI 服务生成代码
        const response = await this.callAIService(prompt)
        
        // 如果 AI 服务返回了代码，直接使用
        if (response && (response.code || response.result)) {
          return response
        }
        
        // 如果没有返回代码，使用模板生成基础代码
        const baseCode = this.generateBaseCode(components, connections, language)
        return { code: baseCode, result: '使用模板生成的基础代码' }
        
      } catch (error) {
        console.error('代码生成失败:', error)
        throw error
      }
    },
    
    // 调用AI服务
    async callAIService(prompt) {
      try {
        const controller = new AbortController()
        const timeoutId = setTimeout(() => controller.abort(), 60000) // 60秒超时
        
        // 检查是否可以使用预设模板
        const templateCode = this.checkForTemplate(prompt)
        if (templateCode) {
          clearTimeout(timeoutId)
          return templateCode
        }

        const response = await fetch('http://localhost:8080/api/generate-code', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ 
            prompt,
            temperature: 0.7,
            max_tokens: 2000
          }),
          signal: controller.signal
        })
        
        clearTimeout(timeoutId)

        if (!response.ok) {
          throw new Error('AI服务请求失败')
        }
        
        const result = await response.json()
        
        if (!result.response) {
          console.error('AI服务返回内容为空')
          const templateCode = this.getPresetTemplate(this.getCurrentCombination(prompt))
          if (templateCode) {
            return templateCode
          }
          return null
        }
        
        return this.parseAIResponse(result.response)
      } catch (error) {
        if (error.name === 'AbortError') {
          console.error('AI服务请求超时')
          const templateCode = this.getPresetTemplate(this.getCurrentCombination(prompt))
          if (templateCode) {
            return templateCode
          }
          throw new Error('AI服务请求超时，正在使用预设模板')
        }
        console.error('AI服务调用失败:', error)
        throw error
      }
    },
    
    // 解析AI响应，提取代码和运行结果
    parseAIResponse(response) {
      try {
        // 确保 response 是字符串
        const responseText = typeof response === 'string' ? response : JSON.stringify(response);
        
        // 格式化代码和结果
        const formatCode = (code) => {
          // 移除多余的转义字符
          code = code.replace(/\\n/g, '\n')
                    .replace(/\\t/g, '\t')
                    .replace(/\\"/g, '"')
                    .replace(/\\\\/g, '\\');
          
          // 如果代码是JSON格式的字符串，尝试解析并美化
          try {
            const jsonObj = JSON.parse(code);
            return JSON.stringify(jsonObj, null, 2);
          } catch (e) {
            // 不是JSON格式，直接返回处理后的代码
            return code;
          }
        };

        // 格式化运行结果为命令行样式
        const formatResult = (result) => {
          try {
            // 尝试解析JSON
            const resultObj = typeof result === 'string' ? JSON.parse(result) : result;
            if (resultObj.result) {
              // 构建命令行风格的输出
              let output = '$ 运行算法\n';
              // 处理原始数组和排序后数组的展示
              if (typeof resultObj.result === 'string') {
                const parts = resultObj.result.split('\n');
                output += parts.map(part => `> ${part}`).join('\n');
              } else {
                output += `> ${JSON.stringify(resultObj.result, null, 2)}`;
              }
              return output;
            }
            return `$ 运行算法\n> ${JSON.stringify(resultObj, null, 2)}`;
          } catch (e) {
            // 如果不是JSON，按普通文本处理
            return `$ 运行算法\n> ${result}`;
          }
        };

        // 根据语言提取代码部分
        const codeMatch = responseText.match(/```(?:java|c|cpp)\s*([\s\S]*?)```/);
        const resultMatch = responseText.match(/运行结果:\s*```\s*([\s\S]*?)```/);
        
        if (!codeMatch) {
          // 如果找不到格式化的代码，格式化整个响应
          return {
            code: formatCode(responseText),
            result: formatResult('未找到格式化的运行结果')
          };
        }
        
        const code = formatCode(codeMatch[1].trim());
        const result = resultMatch ? formatResult(resultMatch[1].trim()) : formatResult('运行成功，无明显输出结果。');
        
        return {
          code,
          result
        };
      } catch (error) {
        console.error('解析AI响应失败:', error);
        return {
          code: typeof response === 'string' ? response : JSON.stringify(response, null, 2),
          result: `$ 运行算法\n> 解析响应失败: ${error.message}`
        };
      }
    },

    buildPrompt(dataStructureNodes, algorithmNodes, connections, language, requestId) {
      if (!dataStructureNodes || !algorithmNodes || dataStructureNodes.length === 0 || algorithmNodes.length === 0) {
        throw new Error('缺少必要的数据结构或算法节点')
      }

      // 找出第一个数据结构和算法
      const dataStructure = dataStructureNodes[0]
      const algorithm = algorithmNodes[0]
      
      if (!dataStructure.data || !algorithm.data) {
        throw new Error('节点数据不完整')
      }

      // 根据不同的数据结构和算法组合构建特定的提示词
      let specificPrompt = '';
      if (dataStructure.type === 'adjacencyMatrix' && algorithm.type === 'bfs') {
        specificPrompt = `
请使用${language}实现基于邻接矩阵的广度优先搜索算法。要求：
1. 邻接矩阵表示无向图
2. 实现广度优先搜索遍历所有可达节点
3. 打印遍历顺序
4. 使用队列实现
5. 包含必要的注释
6. 代码结构清晰，变量命名规范
7. 包含示例测试用例
8. 每次生成不同的测试数据`;
      } else {
        // 通用提示词
        specificPrompt = `请使用${language}实现${dataStructure.data.name}数据结构和${algorithm.data.name}算法的组合应用。
要求：
1. 代码结构清晰，变量命名规范
2. 包含必要的注释
3. 包含示例测试用例
4. 每次生成不同的测试数据
5. 确保代码可以正常运行`;
      }
      
      // 构建完整提示词
      let prompt = `${specificPrompt}
      
请按以下格式返回结果：

\`\`\`${language}
// 这里是完整的${language}代码实现
\`\`\`

运行结果:
\`\`\`
// 这里是代码的运行结果
\`\`\`

代码详细信息:
- 语言: ${language}
- 数据结构: ${dataStructure.data.name}
- 算法: ${algorithm.data.name}
- 配置信息: ${JSON.stringify(dataStructure.data.config)} ${JSON.stringify(algorithm.data.config)}
- 请求ID: ${requestId}
`;

      return prompt;
    },

    generateBaseCode(components, connections, language) {
      let code = ''
      
      // 添加语言特定的头文件
      if (language === 'c') {
        code += '#include <stdio.h>\n#include <stdlib.h>\n\n'
      } else if (language === 'cpp') {
        code += '#include <iostream>\n#include <vector>\n\n'
      }
      
      // 生成数据结构代码
      components.forEach(component => {
        const template = this.codeTemplates[component.type]?.[language]
          if (template) {
          code += this.processTemplate(template, component.config)
          }
      })
      
      // 生成主函数
      if (language === 'c') {
        code += '\nint main() {\n'
        code += '    // 初始化数据结构\n'
        components.forEach(component => {
          const name = component.data.name.toLowerCase()
          code += `    ${component.type}* ${name} = create${component.type}(...);\n`
        })
        code += '\n    // 执行算法\n'
        code += '\n    // 释放内存\n'
        components.forEach(component => {
          const name = component.data.name.toLowerCase()
          code += `    free${component.type}(${name});\n`
        })
        code += '    return 0;\n}'
      } else if (language === 'cpp') {
        code += '\nint main() {\n'
        code += '    // 创建数据结构实例\n'
        components.forEach(component => {
          const name = component.data.name.toLowerCase()
          code += `    ${component.type} ${name}(...);\n`
        })
        code += '\n    // 执行算法\n'
        code += '\n    return 0;\n}'
      } else {
        // Java 代码生成逻辑保持不变
        code += '\npublic class Main {\n'
        code += '    public static void main(String[] args) {\n'
        code += '        // 创建数据结构实例\n'
        components.forEach(component => {
          const name = component.data.name.toLowerCase()
          code += `        ${component.type} ${name} = new ${component.type}(...);\n`
        })
        code += '\n        // 执行算法\n'
        code += '    }\n}'
      }

      return code
    },

    async optimizeWithAI(code, language) {
      try {
        const response = await fetch('http://localhost:8080/api/optimize-code', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ code: code, language: language })
        })
        
        let result
        try {
          result = await response.json()
        } catch (parseError) {
          console.error('解析响应失败:', parseError)
          ElMessage.error('AI服务响应格式错误')
          return code
        }
        
        if (!response.ok) {
          const errorMessage = ERROR_MESSAGES[result.error] || ERROR_MESSAGES.DEFAULT
          ElMessage.error(errorMessage)
          return code
        }
        
        if (!result.optimizedCode) {
          ElMessage.error('AI服务返回内容为空')
          return code
        }
        
        return result.optimizedCode || code
      } catch (error) {
        console.error('AI优化失败:', error)
        ElMessage.error(ERROR_MESSAGES.DEFAULT)
        return code
      }
    },

    // 验证连接是否有效
    validateConnection(source, target) {
      console.log('验证连接:', source, '->', target);
      console.log('连接规则:', this.connectionRules[source]?.outputs);
      
      const sourceComp = this.components.find(c => c.type === source)
      const targetComp = this.components.find(c => c.type === target)
      
      console.log('找到组件:', !!sourceComp, !!targetComp);
      
      if (!sourceComp || !targetComp) return false
      
      const rules = this.connectionRules[source]
      console.log('应用规则:', rules);
      
      if (!rules) return false
      
      return rules.outputs.includes(target)
    },

    addComponent(component) {
      // 添加到连接规则
      if (component.category === 'dataStructure') {
        this.connectionRules[component.type] = {
          outputs: ['bubbleSort', 'quickSort', 'mergeSort', 'binarySearch'],
          description: '可以连接到排序和查找算法组件'
        }
      }

      // 添加到组件列表
      this.components.push({
        id: this.components.length + 1,
        type: component.type,
        name: component.name,
        icon: component.icon || 'Menu',
        config: component.category === 'dataStructure' ? {
          size: 10,
          elementType: 'int',
          elements: []
        } : {
          order: 'asc'
        }
      })
    },

    // 从提示词中提取当前的数据结构和算法组合
    getCurrentCombination(prompt) {
      const dataStructures = ['adjacencyMatrix', 'adjacencyList', 'array', 'binaryTree', 'heap']
      const algorithms = ['dijkstra', 'bubbleSort', 'bfs', 'quickSort', 'dfs', 'mergeSort', 'prim', 'kruskal', 'binarySearch']
      
      let currentDataStructure = ''
      let currentAlgorithm = ''
      let language = 'java'
      
      // 提取数据结构
      for (const ds of dataStructures) {
        if (prompt.includes(ds)) {
          currentDataStructure = ds
          break
        }
      }
      
      // 提取算法
      for (const algo of algorithms) {
        if (prompt.includes(algo)) {
          currentAlgorithm = algo
          break
        }
      }
      
      // 提取语言
      if (prompt.includes('c++')) {
        language = 'cpp'
      } else if (prompt.includes(' c ')) {
        language = 'c'
      }
      
      return { dataStructure: currentDataStructure, algorithm: currentAlgorithm, language }
    },

    // 检查是否可以使用预设模板
    checkForTemplate(prompt) {
      const combination = this.getCurrentCombination(prompt)
      return this.getPresetTemplate(combination)
    },

    // 获取预设的代码模板
    getPresetTemplate({ dataStructure, algorithm, language }) {
      // 邻接矩阵 + BFS
      if (dataStructure === 'adjacencyMatrix' && algorithm === 'bfs') {
        if (language === 'java') {
          return {
            code: this.templates.adjacencyMatrixBfsJava,
            result: '使用预设模板生成的代码'
          }
        }
      }
      
      // 数组 + 冒泡排序
      if (dataStructure === 'array' && algorithm === 'bubbleSort') {
        if (language === 'java') {
          return {
            code: this.templates.arrayBubbleSortJava,
            result: '使用预设模板生成的代码'
          }
        }
      }
      
      // 数组 + 二分查找
      if (dataStructure === 'array' && algorithm === 'binarySearch') {
        if (language === 'java') {
          return {
            code: this.templates.arrayBinarySearchJava,
            result: '使用预设模板生成的代码'
          }
        }
      }
      
      return null
    },

    // 预设模板
    templates: {
      // 邻接矩阵 + BFS的Java模板
      adjacencyMatrixBfsJava: `
public class GraphBFS {
    private int vertices;
    private int[][] adjacencyMatrix;
    
    public GraphBFS(int vertices) {
        this.vertices = vertices;
        this.adjacencyMatrix = new int[vertices][vertices];
    }
    
    // 添加边
    public void addEdge(int v1, int v2) {
        adjacencyMatrix[v1][v2] = 1;
        adjacencyMatrix[v2][v1] = 1; // 无向图
    }
    
    // 广度优先搜索
    public void bfs(int startVertex) {
        boolean[] visited = new boolean[vertices];
        java.util.Queue<Integer> queue = new java.util.LinkedList<>();
        
        visited[startVertex] = true;
        System.out.println("访问顶点: " + startVertex);
        queue.offer(startVertex);
        
        while (!queue.isEmpty()) {
            int currentVertex = queue.poll();
            
            for (int i = 0; i < vertices; i++) {
                if (adjacencyMatrix[currentVertex][i] == 1 && !visited[i]) {
                    visited[i] = true;
                    System.out.println("访问顶点: " + i);
                    queue.offer(i);
                }
            }
        }
    }
    
    public static void main(String[] args) {
        GraphBFS graph = new GraphBFS(6);
        
        // 添加测试边
        graph.addEdge(0, 1);
        graph.addEdge(0, 2);
        graph.addEdge(1, 3);
        graph.addEdge(2, 3);
        graph.addEdge(2, 4);
        graph.addEdge(3, 5);
        
        System.out.println("从顶点0开始BFS遍历:");
        graph.bfs(0);
    }
}`,

      // 数组 + 冒泡排序的Java模板
      arrayBubbleSortJava: `
public class ArrayBubbleSort {
    private int[] array;
    
    public ArrayBubbleSort(int size) {
        this.array = new int[size];
        // 生成随机数据
        java.util.Random random = new java.util.Random();
        for (int i = 0; i < size; i++) {
            array[i] = random.nextInt(100);
        }
    }
    
    public void bubbleSort() {
        int n = array.length;
        boolean swapped;
        
        for (int i = 0; i < n - 1; i++) {
            swapped = false;
            for (int j = 0; j < n - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    // 交换元素
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                    swapped = true;
                }
            }
            // 如果没有交换，说明已经排序完成
            if (!swapped) break;
        }
    }
    
    public void printArray() {
        System.out.println(java.util.Arrays.toString(array));
    }
    
    public static void main(String[] args) {
        ArrayBubbleSort sorter = new ArrayBubbleSort(10);
        System.out.println("原始数组:");
        sorter.printArray();
        
        sorter.bubbleSort();
        
        System.out.println("排序后数组:");
        sorter.printArray();
    }
}`,

      // 数组 + 二分查找的Java模板
      arrayBinarySearchJava: `
public class ArrayBinarySearch {
    private int[] array;
    
    public ArrayBinarySearch(int size) {
        this.array = new int[size];
        // 生成有序数据
        for (int i = 0; i < size; i++) {
            array[i] = i * 2; // 生成有序数列：0, 2, 4, 6, ...
        }
    }
    
    public int binarySearch(int target) {
        int left = 0;
        int right = array.length - 1;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            
            if (array[mid] == target) {
                return mid;
            }
            
            if (array[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        
        return -1; // 未找到目标值
    }
    
    public void printArray() {
        System.out.println(java.util.Arrays.toString(array));
    }
    
    public static void main(String[] args) {
        ArrayBinarySearch searcher = new ArrayBinarySearch(10);
        System.out.println("数组内容:");
        searcher.printArray();
        
        int target = 6; // 要查找的目标值
        int result = searcher.binarySearch(target);
        
        if (result != -1) {
            System.out.println("找到目标值 " + target + " 在索引 " + result);
        } else {
            System.out.println("未找到目标值 " + target);
        }
    }
}`
    }
  }
}) 